package h;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthorizationRedirectFilter extends AuthorizationFilter {
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain fc) throws IOException, ServletException {
		
		boolean passAuth = false;
		HttpServletRequest hReqt = (HttpServletRequest)request;
		HttpServletResponse hResp = (HttpServletResponse)response;

		String queryStr = hReqt.getQueryString();
		if (queryStr!=null&&!queryStr.equals("")){
			queryStr="?"+queryStr.replaceAll("&","%26");
		} else {
			queryStr="";
		}

		if(!auth(hReqt)) {
			hResp.sendRedirect(String.format("%s/login.html?prevpage=%s%s",
					hReqt.getContextPath(),
					hReqt.getRequestURI(),
					queryStr));
		} else {
			passAuth = true;
		}

		if(passAuth) {
			fc.doFilter(request, response);
		}
	}
}
